import React from 'react';
import { connect } from 'dva';
import {
  Col,
  DatePicker,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Radio,
  Row,
  Spin,
  Switch,
  Select,
} from 'antd';
import moment from 'moment';
import styles from '../index.less';
import {
  ActTypeList,
  PriceModeList,
  Lv1ClassifyTypeList,
  ForecastTypeList,
} from '@/pages/Forecast/constants';

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 14 },
};

const DEFAULT_STATE = {
  item: {},
  selectedCity: undefined,
  selectedWarehouse: undefined,
};

const FormItem = Form.Item;

/**
 * Author: feixy
 * Date: 2019-07-11
 * Time: 11:36
 */
@Form.create()
@connect(({ forecastResult, loading, forecastDimension: { cityList, warehouseList } }) => ({
  forecastResult,
  cityList,
  warehouseList,
  loading: loading.models.forecastScheduler,
}))
class DataModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = { ...DEFAULT_STATE };
  }

  componentDidMount() {
    const { item = {} } = this.props;
    if (item.id) {
      this.getById(item.id);
    }
  }

  getById = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'forecastScheduler/getById',
      payload: id,
      callback: data => {
        const { cityId } = data || {};
        this.setState({ item: data, selectedCity: cityId });
      },
    });
  };

  isEdit = () => {
    const { item = {} } = this.state;
    return !!item.id;
  };

  onSaveEvent = () => {
    const { dispatch, handleModalVisible, form, item } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const params = {
        ...fieldsValue,
        forecastDate: fieldsValue.forecastDate.format('YYYY-MM-DD'),
        newGoods: fieldsValue.newGoods ? 1 : 0,
        id: this.isEdit() ? item.id : undefined,
      };
      const event = this.isEdit() ? 'update' : 'add';
      dispatch({
        type: `forecastScheduler/${event}`,
        payload: params,
        callback: ({ data, state }) => {
          if (state === 0) {
            message.success(data);
            handleModalVisible(true);
          } else {
            message.error(data);
          }
        },
      });
    });
  };

  onCityChangeEvent = e => {
    const { form } = this.props;
    this.setState({ selectedCity: e }, () => {
      form.setFieldsValue({ warehouseId: undefined });
    });
  };

  render() {
    const { handleModalVisible, form, cityList, warehouseList, loading } = this.props;
    const { item = {}, selectedCity } = this.state;
    return (
      <Modal
        destroyOnClose
        maskClosable={false}
        width={800}
        okText="保存"
        onOk={this.onSaveEvent}
        onCancel={() => handleModalVisible(false)}
        style={{ top: 20 }}
        visible
        title="新增运营计划"
        className={styles.importModal}
      >
        <Spin spinning={loading} tip="查询中...">
          <Form layout="horizontal">
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item {...formItemLayout} label="预测类型">
                  {form.getFieldDecorator('forecastType', {
                    rules: [{ required: true, message: '请选择预测类型' }],
                    initialValue: item.forecastType,
                  })(
                    <Radio.Group style={{ width: '100%' }} disabled={this.isEdit()}>
                      {ForecastTypeList.filter(record => record.code !== 0).map(record => (
                        <Radio value={record.code} key={record.code}>
                          {record.name}
                        </Radio>
                      ))}
                    </Radio.Group>
                  )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <FormItem key="forecastDate" {...formItemLayout} label="预测日期">
                  {form.getFieldDecorator('forecastDate', {
                    rules: [{ required: true, message: '请选择预测日期' }],
                    initialValue: item.forecastDate ? moment(item.forecastDate) : undefined,
                  })(
                    <DatePicker
                      disabled={this.isEdit()}
                      placeholder="请选择预测日期"
                      disabledDate={current => {
                        return current && current < moment().endOf('day');
                      }}
                    />
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <Form.Item label="一级类目" {...formItemLayout}>
                  {form.getFieldDecorator('lv1ClassifyType', {
                    rules: [{ required: true, message: '请选择一级分类' }],
                    initialValue: item.lv1ClassifyType,
                  })(
                    <Radio.Group style={{ width: '100%' }} disabled={this.isEdit()}>
                      {Lv1ClassifyTypeList.filter(record => record.code !== 0).map(record => (
                        <Radio value={record.code} key={record.code}>
                          {record.name}
                        </Radio>
                      ))}
                    </Radio.Group>
                  )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="城市" {...formItemLayout}>
                  {form.getFieldDecorator('cityId', {
                    rules: [{ required: true, message: '请输入城市ID' }],
                    initialValue: item.cityId,
                  })(
                    <Select
                      disabled={this.isEdit()}
                      placeholder="选择城市"
                      onChange={this.onCityChangeEvent}
                    >
                      {cityList.map(city => (
                        <Select.Option value={city.code} key={city.id}>
                          {city.name}
                        </Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="仓库" {...formItemLayout}>
                  {form.getFieldDecorator('warehouseId', {
                    rules: [{ required: true, message: '请输入仓库Id' }],
                    initialValue: item.warehouseId,
                  })(
                    <Select placeholder="选择仓库" disabled={this.isEdit()}>
                      {warehouseList
                        .filter(warehouse => warehouse.cityCode === selectedCity)
                        .map(warehouse => (
                          <Select.Option value={warehouse.code} key={warehouse.id}>
                            {warehouse.name}
                          </Select.Option>
                        ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="SKU" {...formItemLayout}>
                  {form.getFieldDecorator('sku', {
                    rules: [{ required: true, message: '请输入SKU' }],
                    initialValue: item.sku,
                  })(
                    <InputNumber
                      disabled={this.isEdit()}
                      style={{ width: '100%' }}
                      placeholder="请输入SKU"
                      precision={0}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="SKU名称" {...formItemLayout}>
                  {form.getFieldDecorator('skuName', {
                    rules: [{ required: true, message: '请输入SKU名称' }],
                    initialValue: item.skuName,
                  })(
                    <Input
                      disabled={this.isEdit()}
                      style={{ width: '100%' }}
                      placeholder="请输入SKU名称"
                    />
                  )}
                </Form.Item>
              </Col>

              <Col span={12}>
                <Form.Item label="活动类型" {...formItemLayout}>
                  {form.getFieldDecorator('actType', {
                    rules: [{ required: true, message: '请输入活动类型' }],
                    initialValue: item.actType,
                  })(
                    <Select placeholder="选择活动类型">
                      {ActTypeList.map(actType => (
                        <Select.Option value={actType.code} key={actType.code}>
                          {`${actType.name}(${actType.code})`}
                        </Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="是否新品" {...formItemLayout}>
                  {form.getFieldDecorator('newGoods', {
                    initialValue: item.newGoods === 1,
                    valuePropName: 'checked',
                  })(<Switch unCheckedChildren="否" checkedChildren="是" />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="建议销量" {...formItemLayout}>
                  {form.getFieldDecorator('adviseNum', {
                    initialValue: item.adviseNum,
                  })(
                    <InputNumber
                      style={{ width: '100%' }}
                      placeholder="请输入建议销量"
                      precision={0}
                      min={0}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="售价单价/斤(个)" {...formItemLayout}>
                  {form.getFieldDecorator('singlePrice', {
                    rules: [{ required: false, message: '请输入售价单价/斤(个)' }],
                    initialValue: item.singlePrice,
                  })(
                    <InputNumber
                      style={{ width: '100%' }}
                      placeholder="请输入售价单价/斤(个)"
                      precision={2}
                      min={0}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="成本价单价/斤(个)" {...formItemLayout}>
                  {form.getFieldDecorator('purchasePrice', {
                    rules: [{ required: false, message: '请输入成本价单价/斤(个)' }],
                    initialValue: item.purchasePrice,
                  })(
                    <InputNumber
                      style={{ width: '100%' }}
                      placeholder="请输入成本价单价/斤(个)"
                      precision={2}
                      min={0}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="计价方式" {...formItemLayout}>
                  {form.getFieldDecorator('priceMode', {
                    rules: [{ required: false, message: '请选择计价方式' }],
                    initialValue: item.priceMode,
                  })(
                    <Radio.Group style={{ width: '100%' }}>
                      {PriceModeList.map(record => (
                        <Radio value={record.code} key={record.code}>
                          {record.name}
                        </Radio>
                      ))}
                    </Radio.Group>
                  )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="定价/份" {...formItemLayout}>
                  {form.getFieldDecorator('settlePrice', {
                    rules: [{ required: false, message: '请输入定价/份' }],
                    initialValue: item.settlePrice,
                  })(
                    <InputNumber
                      style={{ width: '100%' }}
                      placeholder="请输入定价/份"
                      precision={2}
                      min={0}
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Spin>
      </Modal>
    );
  }
}

export default DataModal;
